package cn.dglydrpy.study.j2ee.servlet.day09;
/*
 * session监听器:统计当前应用内 session绑定人数
 */

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class CountListener implements HttpSessionListener {//继承HttpSessionListener 实现抽象方法

	public void sessionCreated(HttpSessionEvent arg0) {//session对象创建之后执行 //arg0事件对象
		System.out.println("sessionCreated()");
		
		//先找到session对象
		HttpSession session = arg0.getSession();
		//通过session对象找到上下文
		ServletContext context = session.getServletContext();
		
		//通过上下文获得在线人数
		Integer count = (Integer) context.getAttribute("count");
		
		if (count == null) {
			count = 1;
		} else {
			count++;
		}
		//绑定最新人数
		context.setAttribute("count", count);
	    System.out.println(count);
	}

	public void sessionDestroyed(HttpSessionEvent arg0) {//session对象销毁之后执行
		System.out.println("sessionDestroyed（）");
		ServletContext context = arg0.getSession().getServletContext();
		Integer count =(Integer) context.getAttribute("count");
		if (count>0) {
			count--;
		}
		context.setAttribute("count", count);
	    System.out.println(count);
	}

}
